
<!DOCTYPE html>
<!--[if IEMobile 7 ]><html class="no-js iem7"><![endif]-->
<!--[if lt IE 9]><html class="no-js lte-ie8"><![endif]-->
<!--[if (gt IE 8)|(gt IEMobile 7)|!(IEMobile)|!(IE)]><!--><html class="no-js" lang="en"><!--<![endif]-->
<head>
  <meta charset="utf-8">
  <title>Singleton与多线程 - Yebangyu's Blog</title>
  <meta name="author" content="Yebangyu">

  
  <meta name="description" content="介绍了多线程下如何实现线程安全的singleton">
  <meta name="keywords" content="多线程 singleton模式 多线程">

  <!-- http://t.co/dKP3o1e -->
  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  
  <link rel="canonical" href="http://www.yebangyu.org/blog/2016/12/25/singleton/">
  <link href="/favicon.png" rel="icon">
  <link href="/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">
  <link href="/atom.xml" rel="alternate" title="Yebangyu's Blog" type="application/atom+xml">
  <script src="/javascripts/modernizr-2.0.js"></script>
  <script src="//ajax.lug.ustc.edu.cn/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script>!window.jQuery && document.write(unescape('%3Cscript src="/javascripts/libs/jquery.min.js"%3E%3C/script%3E'))</script>
  <script src="/javascripts/octopress.js" type="text/javascript"></script>
  <!--Fonts from Google"s Web font directory at http://google.com/webfonts -->
<link href="//fonts.lug.ustc.edu.cn/css?family=PT+Serif:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">
<link href="//fonts.lug.ustc.edu.cn/css?family=PT+Sans:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">
<!-- mathjax config similar to math.stackexchange -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
  jax: ["input/TeX", "output/HTML-CSS"],
  tex2jax: {
    inlineMath: [ ['$', '$'] ],
    displayMath: [ ['$$', '$$']],
    processEscapes: true,
    skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
  },
  messageStyle: "none",
  "HTML-CSS": { preferredFont: "TeX", availableFonts: ["STIX","TeX"] }
});
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML" type="text/javascript"></script>

  

</head>

<body   >
  <header role="banner"><hgroup>
  <h1><a href="/">Yebangyu's Blog</a></h1>
  
    <h2>Fond of Concurrency Programming and Machine Learning</h2>
  
</hgroup>

</header>
  <nav role="navigation"><ul class="subscription" data-subscription="rss">
  <li><a href="/atom.xml" rel="subscribe-rss" title="subscribe via RSS">RSS</a></li>
  
</ul>
  
<form action="https://www.google.com/search" method="get">
  <fieldset role="search">
    <input type="hidden" name="sitesearch" value="www.yebangyu.org">
    <input class="search" type="text" name="q" results="0" placeholder="Search"/>
  </fieldset>
</form>
  
<ul class="main-navigation">
  <li><a href="/">Blog</a></li>
  <li><a href="/blog/archives">Archives</a></li>
  <li><a href="/about">About Me</a></li>
</ul>

</nav>
  <div id="main">
    <div id="content">
      <div>
<article class="hentry" role="article">
  
  <header>
    
      <h1 class="entry-title">Singleton与多线程</h1>
    
    
      <p class="meta">
        




<time class='entry-date' datetime='2016-12-25T18:42:32+08:00'><span class='date'><span class='date-month'>Dec</span> <span class='date-day'>25</span><span class='date-suffix'>th</span>, <span class='date-year'>2016</span></span> <span class='time'>6:42 pm</span></time>
        
      </p>
    
  </header>


<div class="entry-content"><p>如果您和我一样，都只有C++背景，之前对设计模式也一窍不通，那么也没有关系，因为本文不需要您对设计模式有多么了解。</p>

<h2 id="singleton">Singleton模式</h2>

<p>所谓的单例模式，single instance模式，简单实现如下：</p>

<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
<span class="line-number">2</span>
<span class="line-number">3</span>
<span class="line-number">4</span>
<span class="line-number">5</span>
<span class="line-number">6</span>
<span class="line-number">7</span>
<span class="line-number">8</span>
<span class="line-number">9</span>
<span class="line-number">10</span>
<span class="line-number">11</span>
<span class="line-number">12</span>
<span class="line-number">13</span>
<span class="line-number">14</span>
<span class="line-number">15</span>
<span class="line-number">16</span>
<span class="line-number">17</span>
</pre></td><td class="code"><pre><code class="c++"><span class="line"><span class="k">class</span> <span class="nc">Singleton</span>
</span><span class="line"><span class="p">{</span>
</span><span class="line">  <span class="k">public</span><span class="o">:</span>
</span><span class="line">    <span class="k">static</span> <span class="n">Singleton</span><span class="o">*</span> <span class="n">instance</span><span class="p">();</span>
</span><span class="line">  <span class="k">private</span><span class="o">:</span>
</span><span class="line">    <span class="k">static</span> <span class="n">Singleton</span><span class="o">*</span> <span class="n">pInstance</span><span class="p">;</span>
</span><span class="line"><span class="p">};</span>
</span><span class="line">
</span><span class="line"><span class="n">Singleton</span><span class="o">*</span> <span class="n">Singleton</span><span class="o">::</span><span class="n">pInstance</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
</span><span class="line">
</span><span class="line"><span class="n">Singleton</span><span class="o">*</span> <span class="n">Singleton</span><span class="o">::</span><span class="n">instance</span><span class="p">()</span>
</span><span class="line"><span class="p">{</span>
</span><span class="line">  <span class="k">if</span> <span class="p">(</span><span class="n">pInstance</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">    <span class="n">pInstance</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Singleton</span><span class="p">();</span>
</span><span class="line">  <span class="p">}</span>
</span><span class="line">  <span class="k">return</span> <span class="n">pInstance</span><span class="p">;</span>
</span><span class="line"><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure></notextile></div>

<!--more-->

<h2 id="singleton-1">多线程下的Singleton模式实现</h2>

<p>以上实现在单线程下运行良好（不考虑构造函数抛异常，注意，本文我们都不考虑C++ Exception）。如果是多线程呢？很自然的，我们想到可以加一把锁，或许就万事大吉了</p>

<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
<span class="line-number">2</span>
<span class="line-number">3</span>
<span class="line-number">4</span>
<span class="line-number">5</span>
<span class="line-number">6</span>
<span class="line-number">7</span>
<span class="line-number">8</span>
<span class="line-number">9</span>
</pre></td><td class="code"><pre><code class="c++"><span class="line"><span class="n">Singleton</span><span class="o">*</span> <span class="n">Singleton</span><span class="o">::</span><span class="n">instance</span><span class="p">()</span>
</span><span class="line"><span class="p">{</span>
</span><span class="line">  <span class="n">LockGuard</span> <span class="n">guard</span><span class="p">(</span><span class="n">yourlock</span><span class="p">);</span>
</span><span class="line">  <span class="k">if</span> <span class="p">(</span><span class="n">pInstance</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">    <span class="n">pInstance</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Singleton</span><span class="p">();</span>
</span><span class="line">  <span class="p">}</span>
</span><span class="line">  <span class="k">return</span> <span class="n">pInstance</span><span class="p">;</span>
</span><span class="line">  <span class="c1">//guard析构，自动调用unlock</span>
</span><span class="line"><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure></notextile></div>

<h2 id="double-check-locking">double check locking</h2>

<p>前面的实现中，存在一个问题：因为只初始化一次，因此大部分情况下其实pInstance都不会为空，只需要简单返回pInstance。既然如此，何必大部分情况下都需要加锁呢？毕竟锁会带来不小的代价的。因此就引入了double check locking，降低锁的使用和冲突，fast path的时候尽最大可能没有任何锁的使用和开销：</p>

<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
<span class="line-number">2</span>
<span class="line-number">3</span>
<span class="line-number">4</span>
<span class="line-number">5</span>
<span class="line-number">6</span>
<span class="line-number">7</span>
<span class="line-number">8</span>
<span class="line-number">9</span>
<span class="line-number">10</span>
<span class="line-number">11</span>
</pre></td><td class="code"><pre><code class="c++"><span class="line"><span class="n">Singleton</span><span class="o">*</span> <span class="n">Singleton</span><span class="o">::</span><span class="n">instance</span><span class="p">()</span>
</span><span class="line"><span class="p">{</span>
</span><span class="line">  <span class="k">if</span> <span class="p">(</span><span class="n">pInstance</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">    <span class="n">LockGuard</span> <span class="n">guard</span><span class="p">(</span><span class="n">yourlock</span><span class="p">);</span>
</span><span class="line">    <span class="k">if</span> <span class="p">(</span><span class="n">pInstance</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">      <span class="n">pInstance</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Singleton</span><span class="p">();</span>
</span><span class="line">    <span class="p">}</span>
</span><span class="line">    <span class="c1">//guard析构，自动调用unlock</span>
</span><span class="line">  <span class="p">}</span>
</span><span class="line">  <span class="k">return</span> <span class="n">pInstance</span><span class="p">;</span>
</span><span class="line"><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure></notextile></div>
<p>如你所见，当pInstance不为空时，不需要任何加锁、释放锁的动作，不过这回得两次检查pInstance是否为空。这是因为：假设线程1执行第三行，发现pInstance为空，还未执行第四行的时候，被调度了出去；线程2执行第三行，发现pInstance为空，获得锁，创建了实例，释放锁；当线程1重新恢复调度的时候，实例已经被创建，这时候它必须再次检查pInstance是否为空，否则就两次创建了，既不符合单例模式的语义，可能还会有其他更严重的问题（资源泄漏可能还算小事）。</p>

<h2 id="memory-reordering">memory reordering</h2>

<p>完美了？看起来很完美，但是问题很大。</p>

<p>注意其中的第6行：</p>

<p><code>pInstance = new Singleton();</code></p>

<p>它不是原子操作。这条语句，从逻辑和功能上包括三个部分：</p>

<p>1，分配内存空间，大小是sizeof(Singleton)</p>

<p>2，在该内存空间上调用Singleton的构造函数，完成初始化。</p>

<p>3，将pInstance指向该内存空间</p>

<p>信不信由你，编译器可能会对这三个步骤进行乱序，乱序后可能出现这样的情况：</p>

<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
<span class="line-number">2</span>
<span class="line-number">3</span>
<span class="line-number">4</span>
<span class="line-number">5</span>
<span class="line-number">6</span>
<span class="line-number">7</span>
<span class="line-number">8</span>
<span class="line-number">9</span>
<span class="line-number">10</span>
<span class="line-number">11</span>
<span class="line-number">12</span>
</pre></td><td class="code"><pre><code class="c++"><span class="line"><span class="n">Singleton</span><span class="o">*</span> <span class="n">Singleton</span><span class="o">::</span><span class="n">instance</span><span class="p">()</span>
</span><span class="line"><span class="p">{</span>
</span><span class="line">  <span class="k">if</span> <span class="p">(</span><span class="n">pInstance</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">    <span class="n">LockGuard</span> <span class="n">guard</span><span class="p">(</span><span class="n">yourlock</span><span class="p">);</span>
</span><span class="line">    <span class="k">if</span> <span class="p">(</span><span class="n">pInstance</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">      <span class="n">pInstance</span> <span class="o">=</span> <span class="k">operator</span> <span class="k">new</span> <span class="p">(</span><span class="k">sizeof</span><span class="p">(</span><span class="n">Singleton</span><span class="p">));</span>
</span><span class="line">      <span class="k">new</span> <span class="p">(</span><span class="n">pInstance</span><span class="p">)</span> <span class="n">Singleton</span><span class="p">();</span>
</span><span class="line">    <span class="p">}</span>
</span><span class="line">    <span class="c1">//guard析构，自动调用unlock</span>
</span><span class="line">  <span class="p">}</span>
</span><span class="line">  <span class="k">return</span> <span class="n">pInstance</span><span class="p">;</span>
</span><span class="line"><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure></notextile></div>
<p>也就是说，乱序后，编译器生成的代码的逻辑是：</p>

<p>1，分配内存单元。</p>

<p>2，将pInstance指向该内存空间。</p>

<p>3，在该内存空间调用构造函数，完成初始化。</p>

<p>乱序后，可能出现如下的data race：线程1执行完第六行后，pInstance不为空；线程2执行第三行判断，发现非空，返回，然而pInstance这时候还没有初始化，这几乎肯定会带来严重的问题。</p>

<h2 id="section">临时变量也于事无补</h2>

<p>你可能想使用一个temp指针来避开这个问题：</p>

<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
<span class="line-number">2</span>
<span class="line-number">3</span>
<span class="line-number">4</span>
<span class="line-number">5</span>
<span class="line-number">6</span>
<span class="line-number">7</span>
<span class="line-number">8</span>
<span class="line-number">9</span>
<span class="line-number">10</span>
<span class="line-number">11</span>
<span class="line-number">12</span>
</pre></td><td class="code"><pre><code class="c++"><span class="line"><span class="n">Singleton</span><span class="o">*</span> <span class="n">Singleton</span><span class="o">::</span><span class="n">instance</span><span class="p">()</span>
</span><span class="line"><span class="p">{</span>
</span><span class="line">  <span class="k">if</span> <span class="p">(</span><span class="n">pInstance</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">    <span class="n">LockGuard</span> <span class="n">guard</span><span class="p">(</span><span class="n">yourlock</span><span class="p">);</span>
</span><span class="line">    <span class="k">if</span> <span class="p">(</span><span class="n">pInstance</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">      <span class="n">Singleton</span> <span class="o">*</span><span class="n">temp</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Singleton</span><span class="p">();</span>
</span><span class="line">      <span class="n">pInstance</span> <span class="o">=</span> <span class="n">temp</span><span class="p">;</span>
</span><span class="line">    <span class="p">}</span>
</span><span class="line">    <span class="c1">//guard析构，自动调用unlock</span>
</span><span class="line">  <span class="p">}</span>
</span><span class="line">  <span class="k">return</span> <span class="n">pInstance</span><span class="p">;</span>
</span><span class="line"><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure></notextile></div>

<p>这下总没有问题了吧？有问题。聪明的非常aggressive的编译器会认为temp在这里是毫无必要的，因此会将它去除，根本不引入任何的temp，乱序还是会发生。</p>

<p>哦，你突然想到，volatile可能可以帮你的忙。因此，你可能将程序变为：</p>

<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
<span class="line-number">2</span>
<span class="line-number">3</span>
<span class="line-number">4</span>
<span class="line-number">5</span>
<span class="line-number">6</span>
<span class="line-number">7</span>
<span class="line-number">8</span>
<span class="line-number">9</span>
<span class="line-number">10</span>
<span class="line-number">11</span>
<span class="line-number">12</span>
<span class="line-number">13</span>
<span class="line-number">14</span>
<span class="line-number">15</span>
<span class="line-number">16</span>
<span class="line-number">17</span>
<span class="line-number">18</span>
<span class="line-number">19</span>
<span class="line-number">20</span>
<span class="line-number">21</span>
</pre></td><td class="code"><pre><code class="c++"><span class="line"><span class="k">class</span> <span class="nc">Singleton</span>
</span><span class="line"><span class="p">{</span>
</span><span class="line">  <span class="k">public</span><span class="o">:</span>
</span><span class="line">    <span class="k">static</span> <span class="k">volatile</span> <span class="n">Singleton</span><span class="o">*</span> <span class="k">volatile</span> <span class="n">instance</span><span class="p">();</span>
</span><span class="line">  <span class="k">private</span><span class="o">:</span>
</span><span class="line">    <span class="k">static</span> <span class="k">volatile</span> <span class="n">Singleton</span><span class="o">*</span> <span class="k">volatile</span> <span class="n">pInstance</span><span class="p">;</span>
</span><span class="line"><span class="p">};</span>
</span><span class="line">
</span><span class="line"><span class="k">volatile</span> <span class="n">Singleton</span><span class="o">*</span> <span class="n">Singleton</span><span class="o">::</span><span class="k">volatile</span> <span class="n">pInstance</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
</span><span class="line"><span class="k">volatile</span> <span class="n">Singleton</span><span class="o">*</span> <span class="k">volatile</span> <span class="n">Singleton</span><span class="o">::</span><span class="n">instance</span><span class="p">()</span>
</span><span class="line"><span class="p">{</span>
</span><span class="line">  <span class="k">if</span> <span class="p">(</span><span class="n">pInstance</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">    <span class="n">LockGuard</span> <span class="n">guard</span><span class="p">(</span><span class="n">yourlock</span><span class="p">);</span>
</span><span class="line">    <span class="k">if</span> <span class="p">(</span><span class="n">pInstance</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">      <span class="k">volatile</span> <span class="n">Singleton</span> <span class="o">*</span><span class="k">volatile</span> <span class="n">temp</span> <span class="o">=</span> <span class="k">new</span> <span class="k">volatile</span> <span class="n">Singleton</span><span class="p">();</span>
</span><span class="line">      <span class="n">pInstance</span> <span class="o">=</span> <span class="n">temp</span><span class="p">;</span>
</span><span class="line">    <span class="p">}</span>
</span><span class="line">    <span class="c1">//guard析构，自动调用unlock</span>
</span><span class="line">  <span class="p">}</span>
</span><span class="line">  <span class="k">return</span> <span class="n">pInstance</span><span class="p">;</span>
</span><span class="line"><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure></notextile></div>

<p>好多volatile，好吓人。简单解释一下：</p>

<p><code>volatile int * volatile p;</code></p>

<p>第一个volatile表明，p指向的内容随时可能会变</p>

<p>第二个volatile表明，p本身可能随时会变（p可能改变所指区域）</p>

<p>好了，temp也是volatile，我们试图这样，让编译器不要乱序。</p>

<p>然而，这是compiler dependent的，它可能会work，也可能不会work。如果它碰巧在我们的环境下是有效的，只能说我们是幸运的，然而它显然不可移植了。</p>

<h2 id="section-1">明确大胆的说出来</h2>

<p>不就是想防止编译器乱序吗？用了那么多volatile看得真心很烦。其实，我们需要的仅仅是一个memory barrier，防止编译器乱序。因此，我们应该显式的告诉编译器，比如这样(以gcc为例)：</p>

<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
<span class="line-number">2</span>
<span class="line-number">3</span>
<span class="line-number">4</span>
<span class="line-number">5</span>
<span class="line-number">6</span>
<span class="line-number">7</span>
<span class="line-number">8</span>
<span class="line-number">9</span>
<span class="line-number">10</span>
<span class="line-number">11</span>
<span class="line-number">12</span>
<span class="line-number">13</span>
</pre></td><td class="code"><pre><code class="c++"><span class="line"><span class="n">Singleton</span><span class="o">*</span> <span class="n">Singleton</span><span class="o">::</span><span class="n">instance</span><span class="p">()</span>
</span><span class="line"><span class="p">{</span>
</span><span class="line">  <span class="k">if</span> <span class="p">(</span><span class="n">pInstance</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">    <span class="n">LockGuard</span> <span class="n">guard</span><span class="p">(</span><span class="n">yourlock</span><span class="p">);</span>
</span><span class="line">    <span class="k">if</span> <span class="p">(</span><span class="n">pInstance</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">      <span class="n">Singleton</span> <span class="o">*</span><span class="n">temp</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Singleton</span><span class="p">();</span>
</span><span class="line">      <span class="n">__asm__</span> <span class="nf">__volatile__</span><span class="p">(</span><span class="s">&quot;&quot;</span> <span class="o">:</span> <span class="o">:</span> <span class="o">:</span> <span class="s">&quot;memory&quot;</span><span class="p">);</span>
</span><span class="line">      <span class="n">pInstance</span> <span class="o">=</span> <span class="n">temp</span><span class="p">;</span>
</span><span class="line">    <span class="p">}</span>
</span><span class="line">    <span class="c1">//guard析构，自动调用unlock</span>
</span><span class="line">  <span class="p">}</span>
</span><span class="line">  <span class="k">return</span> <span class="n">pInstance</span><span class="p">;</span>
</span><span class="line"><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure></notextile></div>
<p>是的，这里需要一个memory barrier，告诉编译器不要乱序。</p>

<p>即使这么做了，可能还是有问题。怎么说？C++标准并没有对多个线程读取同一个变量会发生什么进行任何规定。因此，上面的第3、第5、第8行存在data race，因此这是一个未定义的、不可移植的行为。</p>

<p>BTW，在X86下，问题不大，只要该指针是cacheline aligned即可。</p>

<p>让我们来分析下，在X86下，第3、5、8行的读写同步问题。假设该指针已经cacheline aligned，因此第3、5、8行的读写是原子的。</p>

<p>如果cpu 0上的线程1执行了第8行设置操作，在cpu 1上运行的线程2执行第3行。注意，这时候pInstance的新值对线程2不一定可见。然而这里不会有问题，因为：</p>

<p>1，假如可见，那么第3行if判断不成立，成功返回instance。</p>

<p>2，假如不可见，那么第3行if判断成立，此时pInstance实际上已经不为空，实例已经被创建。线程2尝试加锁操作，成功后，在第5行必然看到pInstance不为空，也就是看到pInstance的新值。</p>

<p>这是由锁的语义保证的：加锁解锁构成了一种synchronize with关系，加锁线程不管处在哪个处理器上，都可以看到上一个不管在哪个处理器上的释放锁的线程对变量的更新后的新值。</p>

<p>值得注意的是，为了防止第3行、第5行的读取pInstance的动作被编译器优化，可以使用<code>ACCESS_ONCE</code>宏。细节可以参考我的<a href="http://www.yebangyu.org/blog/2015/10/31/linux-parallen-programmming-infrastructure/">这篇</a>博客。</p>

<h2 id="c11">C++11来解救</h2>

<p>写出可移植的、线程安全的Singleton，这么难么？在C++11之前，很难。非常难。</p>

<p>现在，有了C++11，有了C++11的memory model，就不算太难了。</p>

<p>熟悉memory model的同学知道，其实我们这里需要的是一个acquire release语义。设置pInstance的时候使用release语义，读取pInstance的时候使用acquire语义。简单实现如下：</p>

<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
<span class="line-number">2</span>
<span class="line-number">3</span>
<span class="line-number">4</span>
<span class="line-number">5</span>
<span class="line-number">6</span>
<span class="line-number">7</span>
<span class="line-number">8</span>
<span class="line-number">9</span>
<span class="line-number">10</span>
<span class="line-number">11</span>
<span class="line-number">12</span>
<span class="line-number">13</span>
<span class="line-number">14</span>
<span class="line-number">15</span>
<span class="line-number">16</span>
<span class="line-number">17</span>
<span class="line-number">18</span>
<span class="line-number">19</span>
<span class="line-number">20</span>
<span class="line-number">21</span>
<span class="line-number">22</span>
<span class="line-number">23</span>
<span class="line-number">24</span>
</pre></td><td class="code"><pre><code class="c++"><span class="line"><span class="k">class</span> <span class="nc">Singleton</span>
</span><span class="line"><span class="p">{</span>
</span><span class="line">  <span class="k">public</span><span class="o">:</span>
</span><span class="line">    <span class="k">static</span> <span class="n">Singleton</span><span class="o">*</span> <span class="n">instance</span><span class="p">();</span>
</span><span class="line">  <span class="k">private</span><span class="o">:</span>
</span><span class="line">    <span class="k">static</span> <span class="n">atomic</span><span class="o">&lt;</span><span class="n">Singleton</span><span class="o">*&gt;</span> <span class="n">pInstance</span><span class="p">;</span>
</span><span class="line"><span class="p">};</span>
</span><span class="line">
</span><span class="line"><span class="n">atomic</span><span class="o">&lt;</span><span class="n">Singleton</span><span class="o">*&gt;</span> <span class="n">Singleton</span><span class="o">::</span><span class="n">pInstance</span><span class="p">;</span>
</span><span class="line">
</span><span class="line"><span class="n">Singleton</span><span class="o">*</span> <span class="n">Singleton</span><span class="o">::</span><span class="n">instance</span><span class="p">()</span>
</span><span class="line"><span class="p">{</span>
</span><span class="line">  <span class="n">Singleton</span><span class="o">*</span> <span class="n">temp</span> <span class="o">=</span> <span class="n">pInstance</span><span class="p">.</span><span class="n">load</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">memory_order_acquire</span><span class="p">);</span>
</span><span class="line">  <span class="k">if</span> <span class="p">(</span><span class="n">temp</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">    <span class="n">LockGuard</span> <span class="n">guard</span><span class="p">(</span><span class="n">yourlock</span><span class="p">);</span>
</span><span class="line">    <span class="n">temp</span> <span class="o">=</span> <span class="n">pInstance</span><span class="p">.</span><span class="n">load</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">memory_order_acquire</span><span class="p">);</span>
</span><span class="line">    <span class="k">if</span> <span class="p">(</span><span class="n">temp</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span><span class="line">      <span class="n">temp</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Singleton</span><span class="p">();</span>
</span><span class="line">      <span class="n">pInstance</span><span class="p">.</span><span class="n">store</span><span class="p">(</span><span class="n">temp</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">memory_order_release</span><span class="p">);</span>
</span><span class="line">    <span class="p">}</span>
</span><span class="line">    <span class="c1">//guard析构，自动调用unlock</span>
</span><span class="line">  <span class="p">}</span>
</span><span class="line">  <span class="k">return</span> <span class="n">temp</span><span class="p">;</span>
</span><span class="line"><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure></notextile></div>

<p>思考：第16行能否使用<code>memory_order_relaxed</code>内存序？</p>

<h2 id="section-2">拓展</h2>

<p>1，查阅资料，了解POSIX中，<code>pthread_once</code>的原理和用法</p>

<p>2，使用volatile的版本中，我们对指针和指针所指之物都加了volatile，也就是：</p>

<p><code>volatile Singleton *volatile p</code></p>

<p>能否改为</p>

<p><code>volatile Singleton *p</code></p>

<p>或者</p>

<p><code>Singleton * volatile p</code></p>

<p>3，查阅资料，解释为什么编译器可能对 <code>pInstance = new Singleton()</code> 进行乱序</p>

<p>4，我们一直没有涉及的一个问题是：pInstance的初始化。它的初始化，是否也可能存在data race？如何避免？</p>

<p>5，不少朋友可能想利用C++11标准中的某个用法：</p>

<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
<span class="line-number">2</span>
<span class="line-number">3</span>
<span class="line-number">4</span>
<span class="line-number">5</span>
</pre></td><td class="code"><pre><code class="c++"><span class="line"><span class="n">Singleton</span><span class="o">&amp;</span> <span class="n">instance</span><span class="p">()</span>
</span><span class="line"><span class="p">{</span>
</span><span class="line">  <span class="k">static</span> <span class="n">Singleton</span> <span class="n">xx</span><span class="p">;</span> <span class="c1">//C++11规定，这个是线程安全的。</span>
</span><span class="line">  <span class="k">return</span> <span class="n">xx</span><span class="p">;</span>
</span><span class="line"><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure></notextile></div>

<p>然而这么做有一些缺点，这些缺点使得这种做法往往不是实现Singleton单例模式的可行方案。读者诸君不妨思考下，这种做法，都有哪些缺点。</p>
</div>


  <footer>
    <p class="meta">
      
  

<span class="byline author vcard">Posted by <span class="fn">Yebangyu</span></span>

      




<time class='entry-date' datetime='2016-12-25T18:42:32+08:00'><span class='date'><span class='date-month'>Dec</span> <span class='date-day'>25</span><span class='date-suffix'>th</span>, <span class='date-year'>2016</span></span> <span class='time'>6:42 pm</span></time>
      

<span class="categories">
  
    <a class='category' href='/blog/categories/bing-xing-bian-cheng/'>并行编程</a>
  
</span>


    </p>
    
      <div class="sharing">
  
  
  
</div>

    
    <p class="meta">
      
        <a class="basic-alignment left" href="/blog/2016/12/04/introductiontohazardpointer/" title="Previous Post: Lock Free中的Hazard Pointer(下)">&laquo; Lock Free中的Hazard Pointer(下)</a>
      
      
        <a class="basic-alignment right" href="/blog/2017/02/17/virtualfunctionandvariadicparametertemplate/" title="Next Post: 虚函数和变长参数模板的妙用">虚函数和变长参数模板的妙用 &raquo;</a>
      
    </p>
  </footer>
</article>


</div>

<aside class="sidebar">
  
    <section>
  <h1>Recent Posts</h1>
  <ul id="recent_posts">
    
      <li class="post">
        <a href="/blog/2017/03/11/2017/">2017技术成长之路</a>
      </li>
    
      <li class="post">
        <a href="/blog/2017/02/17/virtualfunctionandvariadicparametertemplate/">虚函数和变长参数模板的妙用</a>
      </li>
    
      <li class="post">
        <a href="/blog/2016/12/25/singleton/">Singleton与多线程</a>
      </li>
    
      <li class="post">
        <a href="/blog/2016/12/04/introductiontohazardpointer/">Lock Free中的Hazard Pointer(下)</a>
      </li>
    
      <li class="post">
        <a href="/blog/2016/12/03/gccandperfopt/">性能优化的那些传说和迷思</a>
      </li>
    
  </ul>
</section>
<section>
  <h1>Friends' Link</h1>
  <ul>
    <li>
	  <li><a href="http://www.chongh.wiki/">Diting0x</a></li>
	  <li><a href="http://www.xiaolili.net/">wangli</a></li>
	  <li><a href="http://www.skykewei.top">dukewei</a></li>
	  <li><a href="http://irwenqiang.github.io">chenwenqiang</a></li>
      <li><a href="http://www.armsword.com">duruofei</a></li>
    </li>
  </ul>
</section><section>
  <h1>Yebangyu</h1>
  <p>福建人。热爱历史、K歌、NBA</p>
  <p>帝都码农</p>
  <p>历史学家，专治秦汉史</p>
</section>
<section>
 <h1>Categories</h1>
 <ul id="categories">
  <li class='category'><a href='/blog/categories/c-plus-plus/'>c++ (11)</a></li>
<li class='category'><a href='/blog/categories/soupen/'>soupen (4)</a></li>
<li class='category'><a href='/blog/categories/web/'>web (1)</a></li>
<li class='category'><a href='/blog/categories/qi-ta/'>其他 (5)</a></li>
<li class='category'><a href='/blog/categories/li-shi/'>历史 (2)</a></li>
<li class='category'><a href='/blog/categories/bing-xing-bian-cheng/'>并行编程 (20)</a></li>
<li class='category'><a href='/blog/categories/xing-neng-you-hua/'>性能优化 (2)</a></li>
<li class='category'><a href='/blog/categories/suan-fa/'>算法 (4)</a></li>
<li class='category'><a href='/blog/categories/bian-yi-lian-jie/'>编译链接 (2)</a></li>

 </ul>
</section>




  
</aside>


    </div>
  </div>
  <footer role="contentinfo"><!-- mathjax config similar to math.stackexchange -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
  jax: ["input/TeX", "output/HTML-CSS"],
  tex2jax: {
    inlineMath: [ ['$', '$'] ],
    displayMath: [ ['$$', '$$']],
    processEscapes: true,
    skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
  },
  messageStyle: "none",
  "HTML-CSS": { preferredFont: "TeX", availableFonts: ["STIX","TeX"] }
});
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML" type="text/javascript"></script>
<p>
  Copyright &copy; 2017 - Yebangyu -
  <span class="credit">Powered by <a href="http://octopress.org">Octopress</a></span>
</p>
<script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1257548193'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1257548193' type='text/javascript'%3E%3C/script%3E"));</script>

</footer>
  











</body>
</html>
